package com.kuang.sync.singledown;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kuang.controller.ImportControllerInfoController;
import com.kuang.utils.ControllerLogUtils;
import com.kuang.utils.MQTTConnect;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Map;

@Service
@Slf4j
public class SingleDownServiceImpl implements SingleDownService {

    @Value("${mqtt.sfurl}")
    String url;

    @Resource
    MQTTConnect mqttConnect;

    Logger logger = Logger.getLogger(SingleDownServiceImpl.class);

    //设备的注册信息
    @Override
    public String postControllerRegisterSrv(String id, JSONObject preant) throws MqttException {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        String address = "/single/down/ImportControllerRegister";

        preant.put("device_code", id);
        String requestBody = JSON.toJSONString(preant);
        String responseBody="";

        try {
            HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, headers);
            ResponseEntity<String> response = restTemplate.postForEntity(url + address, requestEntity, String.class);
            responseBody = response.getBody();
            // 对响应进行处理
            // 比如转成map
            JSONObject jsonObject = JSONObject.parseObject(responseBody);
            //在这个示例中，我们使用postForEntity()方法发送POST请求，并在请求体中传递了JSON

            JSONObject data = jsonObject.getJSONObject("data");
            String device_code = data.getString("device_code");
            boolean pub = mqttConnect.pub("/single/down/"+device_code, JSON.toJSONString(data));//发布主题


        }catch (Exception e){
            int i = ControllerLogUtils.setErrorMsgLog("post", "/single/down/ImportControllerRegister",
                    "设备的注册信息",e.getMessage(), JSON.toJSONString(preant), JSON.toJSONString(responseBody));
            logger.info("错误信息:"+e.getMessage());

            //发送返回讯息
            JSONObject toJson = new JSONObject();
            JSONObject data = new JSONObject();
            toJson.put("cmd", MapUtils.getString(preant,"cmd"));
            toJson.put("ver",MapUtils.getString(preant,"ver"));
            data.put("state","0");
            toJson.put("data",data);
            boolean pub = mqttConnect.pub("/single/down/"+id, JSON.toJSONString(toJson));//发布主题

            return  null;
        }

        logger.info("信息:"+JSON.toJSONString(responseBody));
        int i = ControllerLogUtils.setMsgLog("post", "/single/down/ImportControllerRegister",
                "设备的注册信息","成功", JSON.toJSONString(preant), JSON.toJSONString(responseBody));
        return null;
    }


    //服务器远程开井返会的讯息
    @Override
    public String postRemoteOpenWellSrv(String id, JSONObject preant) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        String address = "/single/down/getOpenWellResp";

        preant.put("device_code", id);
        String requestBody = JSON.toJSONString(preant);
        String responseBody="";

        try {
            HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, headers);
            ResponseEntity<String> response = restTemplate.postForEntity(url + address, requestEntity, String.class);
            responseBody = response.getBody();
            // 对响应进行处理
            // 比如转成map
            Map<String, Object> map = JSONObject.parseObject(responseBody);
            //在这个示例中，我们使用postForEntity()方法发送POST请求，并在请求体中传递了JSON

            String success = MapUtils.getString(map, "success", "");
            String msg = MapUtils.getString(map, "msg", "");
            if (StringUtils.equals("false",success)){
                int i = ControllerLogUtils.setErrorMsgLog("post", "/single/down/getOpenWellResp",
                        "服务器远程开井返会的讯息",msg, JSON.toJSONString(preant), JSON.toJSONString(responseBody));
                log.info("错误信息:"+msg);
                return  null;
            }

        }catch (Exception e){
            int i = ControllerLogUtils.setErrorMsgLog("post", "/single/down/getOpenWellResp",
                    "服务器远程开井返会的讯息",e.getMessage(), JSON.toJSONString(preant), JSON.toJSONString(responseBody));
            log.info("错误信息:"+e.getMessage());
            return  null;
        }
        int i = ControllerLogUtils.setMsgLog("post", "/single/down/getOpenWellResp",
                "服务器远程开井返会的讯息","成功", JSON.toJSONString(preant), JSON.toJSONString(responseBody));
        log.info("信息:"+JSON.toJSONString(preant));
        return null;
    }

    //服务器远程关井返会的讯息
    @Override
    public String postRemoteCloseWellSrv(String id, JSONObject preant) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        String address = "/single/down/getCloseWellResp";

        preant.put("device_code", id);
        String requestBody = JSON.toJSONString(preant);
        String responseBody="";

        try {
            HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, headers);
            ResponseEntity<String> response = restTemplate.postForEntity(url + address, requestEntity, String.class);
            responseBody = response.getBody();
            // 对响应进行处理
            // 比如转成map
            Map<String, Object> map = JSONObject.parseObject(responseBody);
            //在这个示例中，我们使用postForEntity()方法发送POST请求，并在请求体中传递了JSON

            String success = MapUtils.getString(map, "success", "");
            String msg = MapUtils.getString(map, "msg", "");
            if (StringUtils.equals("false",success)){
                int i = ControllerLogUtils.setErrorMsgLog("post", "/single/down/getCloseWellResp",
                        "服务器远程关井返会的讯息",msg, JSON.toJSONString(preant), JSON.toJSONString(responseBody));
                log.info("错误信息:"+msg);
                return  null;
            }

        }catch (Exception e){
                int i = ControllerLogUtils.setErrorMsgLog("post", "/single/down/getCloseWellResp",
                        "服务器远程关井返会的讯息",e.getMessage(), JSON.toJSONString(preant), JSON.toJSONString(responseBody));
                log.info("错误信息:"+e.getMessage());
            return  null;
        }

        int i = ControllerLogUtils.setMsgLog("post", "/single/down/getCloseWellResp",
                "服务器远程关井返会的讯息","成功", JSON.toJSONString(preant), JSON.toJSONString(responseBody));

        return null;
    }

    /**
     * //2.10 获取设备端信息 cmd=controller_info
     *
     * @param id
     * @param preant
     * @return
     */
    @Override
    public String postControllerInfoSrv(String id, JSONObject preant) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        String address = "/single/down/getDeviceInfoResp";

        preant.put("device_code", id);
        String requestBody = JSON.toJSONString(preant);
        String responseBody="";

        try {
            HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, headers);
            ResponseEntity<String> response = restTemplate.postForEntity(url + address, requestEntity, String.class);
            responseBody = response.getBody();
            // 对响应进行处理
            // 比如转成map
            Map<String, Object> map = JSONObject.parseObject(responseBody);
            //在这个示例中，我们使用postForEntity()方法发送POST请求，并在请求体中传递了JSON

            String success = MapUtils.getString(map, "success", "");
            String msg = MapUtils.getString(map, "msg", "");
            if (StringUtils.equals("false",success)){
                int i = ControllerLogUtils.setErrorMsgLog("post", "/single/down/getDeviceInfoResp",
                        "获取设备端信息",msg, JSON.toJSONString(preant), JSON.toJSONString(responseBody));
                log.info("错误信息:"+msg);
                return  null;
            }

        }catch (Exception e){
            int i = ControllerLogUtils.setErrorMsgLog("post", "/single/down/getDeviceInfoResp",
                    "获取设备端信息",e.getMessage(), JSON.toJSONString(preant), JSON.toJSONString(responseBody));
            log.info("错误信息:"+e.getMessage());
            return  null;
        }

        int i = ControllerLogUtils.setMsgLog("post", "/single/down/getDeviceInfoResp",
                "获取设备端信息","成功", JSON.toJSONString(preant), JSON.toJSONString(responseBody));
        log.info("错误信息:"+JSON.toJSONString(responseBody));
        return null;
    }
}
